<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登录</title>
</head>
<body>
<input type="text" placeholder="输入用户名" id="name">
<input type="password" placeholder="输入密码" id="pwd">
<button id="btn" onclick="login()">登录</button>


<script>

    function login() {
        const name = document.getElementById("name").value
        const pwd = document.getElementById("pwd").value
        if (!name || !pwd) {
            alert("请输入用户名和密码")
            return
        }
        fetch('/login', {
            method: "POST",//请求方式
            headers: {//定制http请求的标头
                "Content-Type": "application/json;charset=UTF-8"
            },
            body: JSON.stringify({name: name, password: pwd})
        }).then(res => res.text()).then(res => {
            if (res) {  // res 不为null再去解析
                let json = JSON.parse(res)
                if (json.id) {
                    location.href = '/'
                }
            } else {
                alert("账号或密码错误")
            }
        })
    }
</script>
</body>
</html>